#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <pthread.h>

#include "error.hpp"
const uint16_t defaultPort = 8080;
const int backlog = 25;

class TcpServer;
class ThreadData
{
public:
    ThreadData(int fd,const std::string &ip,const uint16_t &port,TcpServer *ts)
    :sock(fd),clientip(ip),clientport(port),current(ts)
    {}
public:
    int sock;
    std::string clientip;
    uint16_t clientport;
    TcpServer *current;
};
class TcpServer
{
public:
    TcpServer(uint16_t port = defaultPort) : _port(port)
    {
    }
    void init()
    {
        // 创建
        _sock = socket(AF_INET, SOCK_STREAM, 0);
        if (_sock < 0)
        {
            std::cerr << "create socket error" << std::endl;
            exit(SOCKET_ERR);
        }
        // 绑定
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(_port);
        server.sin_addr.s_addr = INADDR_ANY;
        if (bind(_sock, (struct sockaddr *)&server, sizeof(server)) < 0)
        {
            std::cout << "bind fail" << std::endl;
            exit(BIND_ERR);
        }
        // 监听
        if (listen(_sock, backlog) < 0)
        {
            exit(LISTEN_ERR);
        }
    }
    void start()
    {
        while (true)
        {
            struct sockaddr_in client;
            memset(&client, 0, sizeof(client));
            socklen_t len = sizeof(client);
            // 获取连接
            int clientSock = accept(_sock, (struct sockaddr *)&client, &len);
            if (clientSock < 0)
            {
                std::cerr << "accept failed\n";
                continue;
            }
            // 提取client信息
            std::string clientIP = inet_ntoa(client.sin_addr);
            uint16_t clientPort = client.sin_port;
            // 多线程
            pthread_t tid;
            ThreadData *td = new ThreadData(clientSock, clientIP, clientPort, this);
            pthread_create(&tid, nullptr, threadRoutine, td);
            /*
            //多进程版本
            pid_t pid = fork();
            if (pid < 0)
            {
                // 创建子进程失败就不处理直接关闭clienSock
                close(clientSock);
                continue;
            }
            else if (pid == 0)
            {
                // 子进程会继承父进程的fd，因此要把不需要的fd关闭
                close(_sock);
                if (fork() > 0)
                {
                    exit(0);
                }
                service(clientSock,clientIP,clientPort);
                exit(0);
            }
            // 父进程
            close(clientSock);
            pid_t ret = waitpid(pid, nullptr, 0);
            if (ret == pid)
                std::cout << "wait child " << pid << " success" << std::endl; */
        }
    }
    static void* threadRoutine(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td=static_cast<ThreadData*>(args);
        td->current->service(td->sock,td->clientip,td->clientport);
        return nullptr;
    }
    void service(int sock, const std::string &clientip, uint16_t &clientport)
    {
        // 接受client发来的消息
        char buffer[1024];
        while (true)
        {
            ssize_t n = recv(sock, buffer, sizeof(buffer) - 1, 0);
            // ssize_t n = read(clientSock, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n] = '\0';
                std::string message;
                message = "success receive message from " + clientip + "-" + std::to_string(clientport) + ": " + buffer;
                // 显示接受到的信息
                std::cout << message << std::endl;
                // 回应client
                ssize_t strSize = send(sock, message.c_str(), message.size(), 0);
                if (strSize <= 0)
                {
                    std::cerr << "send fail " << strerror(errno) << std::endl;
                }
            }
            else if (n == 0)
            {
                close(sock);
                std::cerr << "client quit" << std::endl;
                break;
            }
            else
            {
                close(sock);
                std::cerr << "recv error: " << strerror(errno) << std::endl;
                break;
            }
        }
    }
    ~TcpServer()
    {
        close(_sock);
    }

private:
    int _sock;
    uint16_t _port;
};